﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="SubmitSchedulerJobCmdlet.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace CloudBlitz.Powershell.Cmdlets
{
    using System;
    using System.Management.Automation;
    using System.Net;

    using HpcSchedulerManagement.DataContracts;

    [Cmdlet("Submit", "SchedulerJob")]
    public class SubmitSchedulerJobCmdlet : HpcSchedulerCmdletBase
    {
        [Parameter(Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public int JobId { get; set; }

        [Parameter]
        public SchedulerJob Job { get; set; }

        protected override void ProcessRecord()
        {
            try
            {
                base.ProcessRecord();
                this.SubmitSchedulerJobProcess();
            }
            catch (Exception ex)
            {
                this.ThrowTerminatingError(this.HandleException(ex).Result);
            }
        }

        private void SubmitSchedulerJobProcess()
        {
            var client = this.CreateClient();

            var job = this.Job ?? new SchedulerJob();

            NetworkCredential credential = null;
            if (string.IsNullOrEmpty(job.UserName) || string.IsNullOrEmpty(job.Password))
            {
                credential = new NetworkCredential(this.Credentials.AdminLogin, this.Credentials.AdminPassword);
            }

            client.SubmitJob(this.Credentials.ClusterName, this.JobId, job, credential).Wait();
        }
    }
}